<style type="text/css">
    /* 添加子节点的按钮样式 start */
    .ztree li span.button.add {
        margin-left:2px;
        margin-right: -1px;
        background-position:-144px 0;
        vertical-align:top;
        *vertical-align:middle
    }
    /* 添加子节点的按钮样式 end */
    /* 侧边栏 start */
    .left-sidebar{
        width:280px;
        left:0;
        top:40px;
        bottom:0;
        border-right:1px solid #e5e5e5;
        background-color:#f5f5f5;
        overflow:auto;
    }
    .right-content{margin-left:280px;}
    /* 侧边栏 end */
</style>

<nav class="breadcrumb">
    <i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 文章管理 <span class="c-gray en">&gt;</span> 分类管理 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="Hui-iconfont">&#xe68f;</i></a>
</nav>
<!-- 侧边栏 start -->
<div class="pos-a left-sidebar">
    <ul class="ztree">
        <li>
            <a class="js_btn_add">
                <span class="button add" title="添加" style="vertical-align: bottom;"></span>添加根节点
            </a>
        </li>
    </ul>
    <ul id="treeDemo" class="ztree"></ul>
</div>
<!-- 侧边栏 end -->
<div class="right-content">
    <div class="page-container">
        <p class="f-20 text-success">编辑信息：</p>
        <form action="{:url('edit')}" method="post" class="form form-horizontal">
            <div class="row cl">
                <label class="form-label col-xs-4 col-sm-2">分类名称：</label>
                <div class="formControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" name="name" value="" placeholder="">
                </div>
            </div>
            <div class="row cl">
                <label class="form-label col-xs-4 col-sm-2">排序：</label>
                <div class="formControls col-xs-6 col-sm-6">
                    <input type="text" class="input-text" name="sort" value="" placeholder="同一级的排序">
                </div>
            </div>
            <div class="row cl">
                <div class="col-9 col-offset-2">
                    <input type="hidden" name="id" value="">
                    <input class="btn btn-primary radius js_btn_submit" type="button" value="&nbsp;&nbsp;提交&nbsp;&nbsp;">
                </div>
            </div>
        </form>
    </div>
</div>

<!--请在下方写此页面业务相关的脚本-->
<link rel="stylesheet" href="/admin/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css">
<script src="/admin/lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
<script>
    // zTree 的参数配置
    var setting = {
        view: {
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            dblClickExpand: false,//双击不展开
            showLine: false,//不显示节点之间的连线
            selectedMulti: false //禁止（ctrl+单击）同时选中多个节点
        },
        edit: {
            enable: true,
            showRemoveBtn: true,
            showRenameBtn: true,
            removeTitle: '删除',
            renameTitle: '重命名',
            editNameSelectAll: true
        },
        data: {
            simpleData: {
                enable:true,//使用简单的json数据
                idKey: 'id',
                pIdKey: 'pid',//父级id的键
                rootPId: null //（根节点）父级id的值
            }
        },
        callback: {
            beforeRemove: beforeRemove,
            beforeRename: beforeRename,
            beforeClick: function(treeId, treeNode) { //返回是否允许单击
                var zTree = $.fn.zTree.getZTreeObj('treeDemo');
                if (treeNode.isParent) {
                    zTree.expandNode(treeNode);//展开或折叠节点
                }
                //获取该节点的详情
                $('[name="id"]').val('');
                $('[name="name"]').val('');
                $('[name="sort"]').val('');
                $.ajax({
                    url: 'getList',
                    data: {'id': treeNode.id},
                    success: function(response){
                        if (response.code == '1') {
                            //获取成功
                            $('[name="id"]').val(response.data.id);
                            $('[name="name"]').val(response.data.name);
                            $('[name="sort"]').val(response.data.sort);
                        }
                    }
                });
            }
        }
    };
    // zTree 的回调函数
    //删除节点前
    function beforeRemove(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.selectNode(treeNode);
        var flag = false;
        if (confirm("确认删除【" + treeNode.name + "】吗？")) { //注：阻塞
            //ajax提交到后台
            $.ajax({
                url: 'delete',
                data: {'id':treeNode.id},
                async: false,//注：同步
                success: function(response){
                    if (response.code == '1') {
                        //删除成功
                        flag = true;//zTree.removeNode(treeNode);//由于layer.confirm无法阻塞
                        layer.msg(response.msg,{icon:1,time:3000});
                    }else{
                        layer.msg(response.msg,{icon:0,time:3000});
                    }
                },
                error: function(data){
                    layer.msg('发送失败!',{icon:0,time:3000});
                }
            });

        }
        return flag;
    }
    //重命名前（编辑名称结束（Input失去焦点 或 按下Enter键）之后，更新节点名称数据之前）
    function beforeRename(treeId, treeNode, newName, isCancel) {
        if (newName.length == 0) {
            alert('节点名称不能为空！');
            return false;
        }
        if (treeNode.name == newName) { //名称前后不变
            return true;
        }
        if (!isCancel) {
            var flag = false;
            //ajax提交到后台
            $.ajax({
                url: 'edit',
                data: {'id':treeNode.id, 'name':newName},
                async: false,
                success: function(response){
                    if (response.code == '1') {
                        //更新成功
                        flag = true;//这里的return只会renturn其自己的域函数(即success)
                    }else{
                        layer.msg(response.msg,{icon:0,time:3000});
                    }
                },
                error: function(data){
                    layer.msg('发送失败!',{icon:0,time:3000});
                }
            });
            return flag;
        }
    }
    //关于新增
    var newCount = 1;
    //鼠标悬浮节点时，显示（自定义）“+”按钮
    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;//若节点处于编辑名称状态或“+”按钮已存在
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' title='添加' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(){
            var sName = "新建分类" + (newCount++);
            //点击“+”按钮
            $.ajax({
                url: 'add',
                data: {pid:treeNode.id, name:sName},
                async: false,
                success: function(response){
                    if (response.code == '1') {
                        //操作成功
                        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                        zTree.addNodes(treeNode, {id:response.data, pId:treeNode.id, name:sName});
                    }else{
                        layer.msg(response.msg,{icon:0,time:3000});
                    }
                },
                error: function(data){
                    layer.msg('发送失败!',{icon:0,time:3000});
                }
            });
            return false;
        });
    };
    //鼠标移出节点时，隐藏（自定义）“+”按钮
    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    };

    $(function(){
        //ajax获取分类列表
        $.ajax({
            url: 'getList',
            success: function(response){
                if (response.code == '1') {
                    //获取成功
                    var zTree = $.fn.zTree.init($('#treeDemo'), setting, response.data);//实例化zTree
                    var nodes = zTree.getNodes();
                    if (nodes.length>0) {
                        zTree.expandNode(nodes[nodes.length-1], true, true, true);//展开最后一个根节点（包括其全部子节点）
                    }
                }else{
                    layer.msg('无法获取分类列表，请刷新。', {icon:0,time:3000});
                }
            },
            error: function(data){
                layer.msg('发送失败!',{icon:0,time:3000});
            }
        });
        //点击提交按钮
        $(document).on('click', '.js_btn_submit', function(event){
            $form = $(this).parents('form');
            //TODO:判断
            if ($form.find('[name="id"]').val() == '') {
                alert('请选择分类！');
                return false;
            }
            //提交表单
            $.ajax({
                type: $form.attr('method'),
                url: $form.attr('action'),
                data: $form.serialize(),
                success: function(response){
                    if (response.code == '1') {
                        //更新成功
                        layer.msg('更新成功。',{icon:1,time:3000});
                    }else{
                        layer.msg(response.msg,{icon:0,time:3000});
                    }
                },
                error: function(data){
                    layer.msg('发送失败!',{icon:0,time:3000});
                }
            });
        });
        //点击添加根节点
        $(document).on('click', '.js_btn_add', function(event){
            var sName = "新建分类" + (newCount++);
            //提交表单
            $.ajax({
                url: 'add',
                data: {pid:'0', name:sName},
                async: false,
                success: function(response){
                    if (response.code == '1') {
                        //操作成功
                        var zTree = $.fn.zTree.getZTreeObj('treeDemo');
                        zTree.addNodes(null, {id:response.data, pId:'0', name:sName});
                    }else{
                        layer.msg(response.msg,{icon:0,time:3000});
                    }
                },
                error: function(){
                    layer.msg('发送失败!',{icon:0,time:3000});
                }
            });
        });
    });
</script>
<!--请在上方写此页面业务相关的脚本-->